﻿using MySqlConnector;
using SqlSugar;
using System.Data.SqlTypes;
using System.Data;
using Microsoft.SqlServer.Types;

namespace QingZhouLinYe.HttpApi.Models.Converters
{
    public class PointConverter : ISugarDataConverter
    {
        public SugarParameter ParameterConverter<T>(object value, int i)
        {
            var name = "@mylocationp" + i;
            var point = value as Point;
            //var wkt = location != null ? $"POINT ({location.X} {location.Y} {location.Z})" : null;
            var wkt = point != null ? $"POINT ({point.X} {point.Y} {point.Z})" : null;
            // 设置Value为SqlGeometry类型
            SqlGeometry geometry = new SqlGeometry();
            if (point != null)
            {
                //string wkt = "POINT (37.7749 -122.4194)"; // 注意：WKT中的坐标顺序是(X Y)，但在地理上下文中是(经度 纬度)  
                // 创建一个SqlGeometry对象（这里使用WKT表示的点）  
                geometry = SqlGeometry.Parse(new SqlString(wkt));
                geometry.STSrid = 4490;
                geometry.MakeValid(); // MakeValid确保几何体是有效的  
            }
            var parameter = new SugarParameter(name, geometry)
            {
                UdtTypeName = "geometry",
                CustomDbType = System.Data.SqlDbType.Udt,
            };

            return parameter;
        }

        public T? QueryConverter<T>(IDataRecord dr, int i)
        {
            var str = dr.GetValue(i).ToString();
            if (string.IsNullOrWhiteSpace(str))
            {
                return default;
            }

            var parts = str.Replace("POINT(", "").Replace("POINT (", "").Replace("(", "").Replace(")", "").Split(' ');
            if (parts.Length == 3 &&
                double.TryParse(parts[0], out var x) &&
                double.TryParse(parts[1], out var y) &&
                double.TryParse(parts[2], out var z))
            {
                var location = new Point(x, y, z);
                return (T)(object)location;
            }

            return default;
        }


    }
}